using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace IPAMS.Views
{
    /// <summary>
    /// This is an editor for the Charges table. It enables loading from a file,
    ///saving to a file and more
    /// </summary>
    public partial class ChargesEditor : UserControl
    {
        public DSIPAMS.DTChargesDataTable charges;
        string[] chargesHeaders;

        /// <summary>
        /// Initializes a new instance of the <see cref="ChargesEditor"/> class.
        /// </summary>
        public ChargesEditor()
        {
            InitializeComponent();
            InitializeComponentExtneded();
        }

        /// <summary>
        /// Initializes the component extneded.
        /// </summary>
        private void InitializeComponentExtneded()
        {
            charges = new DSIPAMS.DTChargesDataTable();
            dgvCharges.DataSource = charges;
        }

        /// <summary>
        /// Handles the DataSourceChanged event of the dgvCharges control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void dgvCharges_DataSourceChanged(object sender, EventArgs e)
        {
            dgvCharges.Refresh();
        }


        /// <summary>
        /// Loads the data from a file.
        /// </summary>
        /// <param name="dataFilePath">The data file path.</param>
        /// <returns>a DataTable with the file's data</returns>
        public DataTable LoadData(string dataFilePath)
        {
            if (File.Exists(dataFilePath))
            {
                StreamReader sr;
                try
                {
                    sr = new StreamReader(dataFilePath);
                    chargesHeaders = sr.ReadLine().Split(',');

                    while (true)
                    {
                        string charge = sr.ReadLine();
                        if (charge == string.Empty || charge == null) break;
                        string[] chargeInfo = charge.Split(',');
                        if (chargeInfo.Length != chargesHeaders.Length) continue;

                        string investmentHouseSymbol = chargeInfo[0];
                        string chargeType = chargeInfo[1];
                        string minimal = chargeInfo[2] != string.Empty ? chargeInfo[2] : "0";
                        string maximal = chargeInfo[3] != string.Empty ? chargeInfo[3] : "0";
                        string rate = chargeInfo[4] != string.Empty ? chargeInfo[4] : "0";
                        string value = chargeInfo[5] != string.Empty ? chargeInfo[5] : "0";
                        string monthlyPeriod = chargeInfo[6] != string.Empty ? chargeInfo[6] : "0";
                        string perStock = chargeInfo[7] != string.Empty ? chargeInfo[7] : "0";

                        CultureInfo ci = new CultureInfo("he-IL");
                      
                        charges.AddDTChargesRow(investmentHouseSymbol,
                                                chargeType,
                                                Convert.ToDouble(minimal),
                                                Convert.ToDouble(maximal),
                                                Convert.ToDouble(rate),
                                                Convert.ToDouble(value),
                                                Convert.ToInt32(monthlyPeriod),
                                                Convert.ToDouble(perStock),
                                                DateTime.Parse(chargeInfo[8],ci.DateTimeFormat),
                                                DateTime.Parse(chargeInfo[9],ci.DateTimeFormat), chargeInfo[10]);
                    }
                    sr.Close();
                    Text = dataFilePath;


                    dgvCharges.DataSource = charges;
                    for (int index = 0; index < chargesHeaders.Length; index++)
                    {
                        dgvCharges.Columns[index].HeaderText = chargesHeaders[index];
                    }

                    foreach (DataGridViewColumn column in dgvCharges.Columns)
                    {
                        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    }
                    charges.AcceptChanges();
                }
                catch (IOException ioException)
                {
                    MessageBox.Show("One or more files are being used by another application,\nPlease close all files and restart.",
                                    "File being used error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                   // throw new Exception("One or more files are being used by another application.",ioException);
                }
                
            }
           
           
            return charges;
        }

        /// <summary>
        /// Saves the data to a file.
        /// </summary>
        /// <param name="dataFilePath">The data file path.</param>
        public void SaveData(string dataFilePath)
        {
            StreamWriter sw = new StreamWriter(dataFilePath);
            string fileContent = chargesHeaders + Environment.NewLine;
            foreach (DSIPAMS.DTChargesRow charge in charges)
            {
                fileContent += string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}" + Environment.NewLine,
                    charge[0], charge[1], charge[2], charge[3],
                    charge[4], charge[5], charge[6], charge[7], charge[8], charge[9]);
            }
            sw.Write(fileContent);
            sw.Close();

        }

    }
    
}
